﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AoYing_DeviceCollection
{
    public partial class MKDeviceCollectionForm : Form
    {
        public MKDeviceCollectionForm()
        {
            InitializeComponent();

            BaseUtils._eventMsg.InfoHandler += EventMsg_Info;
            BaseUtils._eventMsg.ErrorMsgHandler += EventMsg_Error;
            BaseUtils._eventMsg.LogProcess = "锦飞";

            CheckForIllegalCrossThreadCalls = false; // 解除非窗口线程操作控件的限制
        }

        private async void button1_Click(object sender, EventArgs e)
        {
        
            await CollectionMethodAsync();
        }

        #region ListBox信息填充
        private void EventMsg_Error(object sender, EventArgs e)
        {
            try
            {
                if (LB_Error.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        WriteListBox(LB_Error, BaseUtils._eventMsg.ErrorMsg);
                    }));
                }
                else
                {
                    WriteListBox(LB_Error, BaseUtils._eventMsg.ErrorMsg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error($"【处理失败提示出错】{ex.Message}------{ex.StackTrace}");
            }
        }

        private void EventMsg_Info(object sender, EventArgs e)
        {
            try
            {
                if (LB_Success.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        WriteListBox(LB_Success, BaseUtils._eventMsg.Info);
                    }));
                }
                else
                {
                    WriteListBox(LB_Success, BaseUtils._eventMsg.ErrorMsg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error($"【处理成功提示出错】{ex.Message}------{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 写提示信息，同样信息不会重复生成
        /// </summary>
        /// <param name="listBox"></param>
        /// <param name="message"></param>
        private void WriteListBox(ListBox listBox, string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            if (listBox.Items.Count < 1)
            {
                listBox.Items.Insert(0, $"{DateTime.Now}-{message}");
                if (listBox.Name.Contains("Error"))
                {
                    new LogHelper().Error(message);

                }
                else
                {
                    new LogHelper().Info(message);

                }
                return;
            }
            var lastMessage = listBox.Items[0].ToString();
            if (lastMessage.Contains(message))
            {
                return;
            }

            listBox.Items.Insert(0, $"{DateTime.Now}-{message}");
            if (listBox.Name.Contains("Error"))
            {
                new LogHelper().Error(message);
            }
            else
            {
                new LogHelper().Info(message);
            }
        }
        #endregion

        #region 页面加载动作
        private  void Form1_Load(object sender, EventArgs e)
        {

            try
            {
           
                comboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged;
                comboBox2.SelectedIndexChanged += ComboBox2_SelectedIndexChanged;
                comboBox2.KeyDown += ComboBox2_KeyDown;
                InitializeComboBox();
                button1.BackColor = Color.White;

            }
            catch (Exception ex)
            {
                BaseUtils._eventMsg.ErrorMsg = "锦飞采集Form加载异常" + ex.Message;
                MessageBox.Show("锦飞采集Form加载异常" + ex.Message);

            }
        }
        private void InitializeComboBox()
        {
            #region 线体下拉框绑定
            DataTable areaInfoDt = CommonHelper.GetDataTable($"select AreaName from  sysdatarea ;");
            // 清空ComboBox中的旧数据
            comboBox1.Items.Clear();
            // 确保DataTable中有数据后再进行绑定
            if (areaInfoDt.Rows.Count > 0)
            {
                // 遍历DataTable并将DeviceId添加到ComboBox
                foreach (DataRow row in areaInfoDt.Rows)
                {
                    comboBox1.Items.Add(row["AreaName"].ToString());
                }
                // 可选：设置ComboBox默认选中第一项
                // comboBox1.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("未找到相关线体信息！");
            }

            #endregion


        }

        // 处理 comboBox1 选中项变化事件
        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 获取 comboBox1 选中的值
            string selectedValue = comboBox1.SelectedItem.ToString();

            // 根据 comboBox1 选中的值来填充 comboBox2
            UpdateComboBox2(selectedValue);
        }
        // 处理 comboBox1 选中项变化事件
        private void ComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (SmtMachine_Gather.mkState == true)
            {
             
                button1.BackColor = Color.White;
                button1.Text = "执行";
                SmtMachine_Gather.aoi2dState = false;
                MessageBox.Show("正在运行的采集已经暂停！");

            }

        }
        private void UpdateComboBox2(string selectedValue)
        {
            DataTable devicInfoDt = CommonHelper.GetDataTable($"select WOCode from  sfcdatwocode where Status='6' AND  AreaName='{selectedValue}';");
            // 清空ComboBox中的旧数据
            comboBox2.Items.Clear();
            // 确保DataTable中有数据后再进行绑定
            if (devicInfoDt.Rows.Count > 0)
            {
                // 遍历DataTable并将DeviceId添加到ComboBox
                foreach (DataRow row in devicInfoDt.Rows)
                {
                    comboBox2.Items.Add(row["WOCode"].ToString());
                }

            }
            else
            {
                MessageBox.Show("未找到工单信息！");
            }
        }

        // 处理 comboBox2 按键事件
        private async void ComboBox2_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下回车键
            if (e.KeyCode == Keys.Enter)
            {
                await CollectionMethodAsync();
            }
        }


        public async Task CollectionMethodAsync()
        {
            button1.BackColor = Color.Green;
            button1.Text = "采集运行中";
            SmtMachine_Gather.mkState = true;
            string DeviceId = ConfigurationManager.AppSettings["DeviceId"];
            string wocode = comboBox2.SelectedItem.ToString();
            DataTable configDt = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceId='{DeviceId}' ;");
            if (configDt.Rows.Count != 0)
            {
                await Task.Run(() => SmtMachine_Gather.JF_MK_GatherSmtMachine(configDt.Rows[0], wocode));
            }
            else
            {

                MessageBox.Show("该设备id没有采集路径配置");
            }

        }

        #endregion


        /// <summary>
        /// 页面关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceCollectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}
